# -*- coding: UTF-8 -*-
import json
import time
import tkinter as tk
from tkinter import ttk
from threading import Thread
import requests
from win_mac import Mac
from server import MyService


def formatForm(form, width, heigth):
    """设置居中显示"""
    # 得到屏幕宽度
    win_width = form.winfo_screenwidth()
    # 得到屏幕高度
    win_higth = form.winfo_screenheight()
 
    # 计算偏移量
    width_adjust = (win_width - width) / 2
    higth_adjust = (win_higth - heigth) / 2
 
    form.geometry("%dx%d+%d+%d" % (width, heigth, width_adjust, higth_adjust))

class MakeGui(object):

    def __init__(self, init_window:tk.Tk):
        self.init_window = init_window
        self.init_window.title("mac服务")
        self.init_window.geometry('500x300')
        formatForm(self.init_window,500, 300)
        self.loading = LoadingBar()
        
        # Create a label widget
        self.label = tk.Label(self.init_window, text="服务已启动："+Mac.load_mac())
        # Pack the label into the main window
        self.label.pack(pady=10)
        
        # Create a button widget
        # buttonStart = tk.Button(window, text="启动", command=lambda: self.thread_it(self.startService))
        # buttonStart.pack(pady=10)

        button = tk.Button(self.init_window, text="检测", command=lambda: self.thread_it(self.checkService))
        
        # Pack the button into the main window
        button.pack(pady=10)

        self.labelCheck = tk.Label(self.init_window, text="")
        # Pack the label into the main window
        self.labelCheck.pack(pady=10)

        self.thread_it(self.startService)

    def startService(self):
        MyService.run()

    def thread_it(self, func, *args):
        """ 将函数打包进线程 """
        self.myThread = Thread(target=func, args=args)
        self.myThread .setDaemon(True)  # 主线程退出就直接让子线程跟随退出,不论是否运行完成。
        self.myThread .start()

    
    def checkService(self):
        self.loading.show(speed=5)
        res = requests.get('http://127.0.0.1:8249/mac')
        if res.status_code==200:
            text = res.json()
            print(text)
            print(text['data'])
            self.labelCheck.config(text="检测结果:mac地址为"+str(text['data']))
        self.loading.close()


class LoadingBar(object):
 
    def __init__(self, width=200):
        # 存储显示窗体
        self.__dialog = None
        # 记录显示标识
        self.__showFlag = True
        # 设置滚动条的宽度
        self.__width = width
        # 设置窗体高度
        self.__heigth = 20
 
    def show(self, speed=10, sleep=0):
        """显示的时候支持重置滚动条速度和标识判断等待时长"""
        # 防止重复创建多个
        if self.__dialog is not None:
            return
 
        # 线程内读取标记的等待时长（单位秒）
        self.__sleep = sleep
 
        # 创建窗体
        self.__dialog = tk.Toplevel()
        # 去除边框
        self.__dialog.overrideredirect(-1)
        # 设置置顶
        self.__dialog.wm_attributes("-topmost", True)
        formatForm(self.__dialog, self.__width, self.__heigth)
        # 实际的滚动条控件
        self.bar = ttk.Progressbar(self.__dialog, length=self.__width, mode="indeterminate",
                                   orient=tk.HORIZONTAL)
        self.bar.pack(expand=True)
        # 数值越小，滚动越快
        self.bar.start(speed)
        # 开启新线程保持滚动条显示
        t = Thread(target=self.waitClose)
        t.setDaemon(True)
        t.start()
 
    def waitClose(self):
        # 控制在线程内等待回调销毁窗体
        while self.__showFlag:
            time.sleep(self.__sleep)
 
        # 非空情况下销毁
        if self.__dialog is not None:
            self.__dialog.destroy()
 
        # 重置必要参数
        self.__dialog = None
        self.__showFlag = True
 
    def close(self):
        # 设置显示标识为不显示
        self.__showFlag = False

if __name__=='__main__':
    init_window = tk.Tk()
    # init_window.attributes("-topmost", 1)
    test_gui = MakeGui(init_window)
    init_window.mainloop()